import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/localization/default_localizations.dart';
import 'package:flutterlib/common/net/dao_result.dart';
import 'package:flutterlib/common/net/retrofit/post_api.dart';
import 'package:flutterlib/common/style/font_awesome4_icons.dart';
import 'package:flutterlib/common/style/meterial_design_icons.dart';
import 'package:flutterlib/common/style/quhui_style.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/app_version.dart';
import 'package:flutterlib/model/interest/interest_join.dart';
import 'package:flutterlib/model/post/comment_request.dart';
import 'package:flutterlib/model/post/post_detail_bean.dart';
import 'package:flutterlib/pages/interest/viewmodel/interest_store.dart';
import 'package:flutterlib/pages/post/viewmodel/post_store.dart';
import 'package:flutterlib/widgets/bussiness/post/comment_list_item.dart';
import 'package:flutterlib/widgets/bussiness/user_info_widget.dart';
import 'package:flutterlib/widgets/dialog/flutter_custom_dialog.dart';
import 'package:flutterlib/widgets/dialog/heart_dialog.dart';
import 'package:flutterlib/widgets/dialog/input_dialog.dart';
import 'package:flutterlib/widgets/pull/nested/simple_pull_load_manger.dart';
import 'package:flutterlib/widgets/pull/nested/simple_pull_load_page_widget.dart';
import 'package:like_button/like_button.dart';
import 'package:mobx/mobx.dart';
import 'package:share/share.dart';

enum BackActionEnum { MODIFY, DELETE }

class Page extends StatefulWidget {
  final int postId;
  final String title;

  Page({Key key, this.postId, this.title: ""}) : super(key: key);

  @override
  PageState createState() => PageState();
}

///页面 KeepAlive ，同时支持 动画Ticker
class PageState extends State<Page> with TickerProviderStateMixin {
  SimplePullLoadManger manger;
  final PostStore store = PostStore();
  final InterestStore interestStore = InterestStore();
  PostDetailBean post;
  final SettingsStore settingStore =
      Provider.of<SettingsStore>(currentContext, listen: false);

  ///滑动监听
  final ScrollController scrollController = new ScrollController();

  getDataLogic(int page) async {
    print(page);

    var posts = await PostApi.builder()
        .commentPageByQuery(widget.postId, page - 1, "createTime,desc");
    return new DataResult(posts.content, true);
  }

  Widget renderItem(index, comment) {
    //提交
    // var post = pullLoadWidgetControl.dataList[index];
    return CommentListItem(
      comment,
      onUserPressed: () {},
      onCommentReplyPressed: () {
        InputDialog.show(context).then((value) {
          if (value == null || value.isEmpty) {
            return;
          }
          CommentRequest request = new CommentRequest(
              content: value,
              postId: widget.postId,
              userId: currentUserId,
              author: currentUser.nickName,
              parentId: comment.id);
          ObservableFuture writeComment = store.writeComment(request);
          writeComment.then((value) {
            trueDebugPrint("flutterting write comment then call");
          }).catchError((e) {
            trueDebugPrint("flutterting write comment error $e");
          });
          writeComment.whenComplete(() {
            showCenterToast("评论成功!");
            // setState(() {
            //需要插入到指定comment的children中
            // showCenterToast("评论成功!");
            // });
          });
        });
      },
    );
  }

  @override
  void initState() {
    super.initState();
    manger = SimplePullLoadManger.needSliverHeader(
      getDataLogic: getDataLogic,
      renderItem: renderItem,
      renderHeader: renderHeader,
      renderEmpty: renderEmptyView,
    );
    store.fetchPostDetail(widget.postId);
    PostApi.builder().increaseVisit(widget.postId);
  }

  getHtmlWidget(String content) {
    return HtmlWidget(
      // the first parameter (`html`) is required
      content,

      // set the default styling for text
      textStyle: TextStyle(fontSize: 14),

      // By default, `webView` is turned off because additional config
      // must be done for `PlatformView` to work on iOS.
      // https://pub.flutter-io.cn/packages/webview_flutter#ios
      // Make sure you have it configured before using.
      webView: true,
    );

    // Html(
    // data: content,
    // //Optional parameters:
    // onLinkTap: (url) {
    //   // open url in a webview
    // },
    // onImageTap: (src) {
    //   // Display the image in large form.
    // },
    // );
  }

  Widget renderEmptyView(BuildContext context) {
    return new Container(
      height: 350.h,
      alignment: Alignment.center,
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            child: Text("数据为空", style: QuhuiConstant.normalText),
          ),
        ],
      ),
    );
  }

  ///绘制内置Header，支持部分停靠支持
  List<Widget> renderHeader(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverToBoxAdapter(
        child: Container(
          color: QuhuiColors.white,
          child: Observer(
            builder: (_) {
              var future = store.postDetailFuture;
              switch (future.status) {
                case FutureStatus.pending:
                  return Container();
                case FutureStatus.fulfilled:
                  post = future.result;
                  return Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(15, 12, 15, 12),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                UserInfoWidget(
                                  onPressed: () {
                                    NavigatorUtils.goUserHome(
                                        context, post.userId);
                                  },
                                  width: 33,
                                  height: 33,
                                  image: post.userLogo,
                                ),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      post.userName,
                                      style: QuhuiConstant.smallText,
                                    ),
                                    Text(
                                      DateUtil.formatDateMs(post.createTime,
                                          format: DateFormats.y_mo_d),
                                      style: QuhuiConstant.smallSubText,
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.fromLTRB(0, 15, 0, 0),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    post.title,
                                    style: QuhuiConstant.normalTextBold,
                                  ),
                                  getHtmlWidget(post.originalContent),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        height: 10,
                        color: QuhuiColors.grayColor,
                      ),
                      Container(
                        width: double.infinity,
                        height: 39,
                        color: QuhuiColors.white,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 21.0),
                            child: Text(
                              "回复" + post.commentCount.toString(),
                              style: QuhuiConstant.normalText,
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Container(
                          color: QuhuiColors.dividerColor,
                          width: double.infinity,
                          height: 0.3,
                        ),
                      ),
                    ],
                  );
              }
              return Container();
            },
          ),
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    YYDialog.init(context);
    return new Scaffold(
      bottomNavigationBar: SizedBox(
        height: 49,
        child: Observer(
          builder: (_) {
            var future = store.postDetailFuture;
            switch (future.status) {
              case FutureStatus.fulfilled:
                post = future.result;
                return _getBottomWidget();
              default:
                return Container();
            }
          },
        ),
      ),
      appBar: AppBar(
        // leading: MyBackButton(color: Colors.black),
        backgroundColor: QuhuiColors.white,
        title: Observer(builder: (_) {
          var future = store.postDetailFuture;
          switch (future.status) {
            case FutureStatus.fulfilled:
              post = future.result;
              var interestFromId = getInterestFromId(post.interestId);
              return Text(
                interestFromId?.name ?? "",
                style: QuhuiConstant.smallText,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              );
            default:
              return Text(
                "",
                style: QuhuiConstant.smallText,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              );
          }
        }),
        titleSpacing: 0,
        centerTitle: false,
        actions: [
          _buildInterestBtn(context),
          _buildMoreAction(context),
          SizedBox(
            width: 15,
          )
        ],
      ),
      body: Container(
        color: QuhuiColors.white,
        child: SimplePullLoadWidget(
          pullLoadManger: manger,
        ),
      ),
    );
  }

  Widget _buildInterestBtn(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: Observer(
        builder: (_) {
          var joinInterestFuture = interestStore.joinInterestFuture;
          return joinInterestFuture == null
              ? FlatButton(
                  color: QuhuiColors.mainThemeColor,
                  highlightColor: Colors.green[700],
                  colorBrightness: Brightness.dark,
                  splashColor: Colors.grey,
                  padding: EdgeInsets.all(0),
                  child: Text(
                    "+兴趣",
                    style: QuhuiConstant.smallTextWhite,
                  ),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0)),
                  onPressed: () {
                    if (!isLogin) {
                      NavigatorUtils.goLogin(context);
                      return;
                    }
                    InterestJoin join =
                        InterestJoin(interestId: post.interestId);
                    interestStore.joinInterest(join).then((value) {
                      if (value) {
                        settingStore
                            .addInterest(getInterestFromId(post.interestId));
                      } else {
                        ToastUtils.error("加入失败");
                      }
                    });
                  },
                )
              : FlatButton(
                  color: QuhuiColors.mainThemeColor,
                  highlightColor: Colors.green[700],
                  colorBrightness: Brightness.dark,
                  splashColor: Colors.grey,
                  padding: EdgeInsets.all(0),
                  child: Text(
                    "已加入",
                    style: QuhuiConstant.smallTextWhite,
                  ),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0)),
                  onPressed: () {},
                );
        },
      ),
    );
  }

  ///获取底部状态控件显示
  _getBottomWidget() {
    Widget bottomWidget = Padding(
      padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                if (!isLogin) {
                  NavigatorUtils.goLogin(context);
                  return;
                }
                InputDialog.show(context).then((value) {
                  if (value == null || value.isEmpty) {
                    return;
                  }
                  CommentRequest request = new CommentRequest(
                      content: value,
                      postId: widget.postId,
                      userId: currentUserId,
                      author: currentUser.nickName);
                  ObservableFuture writeComment = store.writeComment(request);
                  writeComment.then((value) {
                    trueDebugPrint("flutterting write comment then call");
                  }).catchError((e) {
                    trueDebugPrint("flutterting write comment error $e");
                  });
                  writeComment.whenComplete(() {
                    setState(() {
                      manger.dataList.insert(0, store.commentFuture.result);
                      // showCenterToast("评论成功!");
                    });
                  });
                });
              },
              child: Container(
                margin: EdgeInsets.fromLTRB(0, 12, 0, 12),
                padding: EdgeInsets.only(left: 5),
                height: double.infinity,
                decoration: BoxDecoration(
                    color: QuhuiColors.minGrayColor,
                    borderRadius: BorderRadius.all(Radius.circular(3))),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    QuhuiLocalizations.of(context)
                        .currentLocalized
                        .write_comment,
                    style: QuhuiConstant.minSubGrayText,
                  ),
                ),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(21, 0, 15, 0),
            child: StatefulBuilder(
              builder: (context, _setState) {
                return LikeButton(
                    isLiked: post.isLiked,
                    onTap: (islike) {
                      return onZhanPressed(islike, _setState);
                    },
                    size: 50,
                    circleColor: CircleColor(
                        start: Color(0xff00ddff), end: Color(0xff0099cc)),
                    bubblesColor: BubblesColor(
                      dotPrimaryColor: Color(0xff33b5e5),
                      dotSecondaryColor: Color(0xff0099cc),
                    ),
                    likeBuilder: (bool isLiked) {
                      return Icon(
                        MIcon.thumb_up,
                        color: isLiked ? Colors.red : Colors.grey,
                      );
                    },
                    likeCount: post.likes,
                    countBuilder: (int count, bool isLiked, String text) {
                      Widget result;
                      if (count == 0) {
                        result = Text(
                          "0",
                          style: QuhuiConstant.minSubText,
                        );
                      } else
                        result = Text(
                          text,
                          style: QuhuiConstant.minSubText,
                        );
                      return result;
                    });
              },
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
            child: StatefulBuilder(
              builder: (context, _setState) {
                return Center(
                  child: InkWell(
                    onTap: () {
                      onCollectPressed(_setState);
                    },
                    child: Container(
                      width: 50,
                      height: 50,
                      alignment: Alignment.center,
                      child: post.isCollect
                          ? Icon(
                              Icons.star,
                              color: QuhuiColors.textColorRed,
                            )
                          : Icon(
                              AIcon.star_empty,
                            ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
    return bottomWidget;
  }

  Future<bool> onZhanPressed(isLike, setState) async {
    if (!isLogin) {
      NavigatorUtils.goLogin(context);
      return false;
    }
    if (!post.isLiked) {
      var likeBean = await PostApi.builder().like(post.id);
      setState(() {
        post.isLiked = true;
        if (likeBean != null && likeBean.match) {
          // ToastUtils.success("加为好友");
          HeartDialog.show(
            context,
            text: '互赞加为好友',
          );
        }
      });
    } else {
      await PostApi.builder().unLike(post.id);
      setState(() {
        post.isLiked = false;
      });
    }
    return !isLike;
  }

  onCollectPressed(setState) async {
    if (!isLogin) {
      NavigatorUtils.goLogin(context);
      return false;
    }
    if (!post.isCollect) {
      await PostApi.builder().collect(post.id);
      setState(() {
        post.isCollect = true;
      });
    } else {
      await PostApi.builder().unCollect(post.id);
      setState(() {
        post.isCollect = false;
      });
    }
  }

  _buildMoreAction(BuildContext context) {
    return Observer(builder: (_) {
      var future = store.postDetailFuture;
      switch (future.status) {
        case FutureStatus.fulfilled:
          post = future.result;
          bool isAuthor = currentUser != null && currentUserId == post.userId;
          bool isDraft = post.status == 'DRAFT';
          return (isAuthor && isDraft)
              ? InkWell(
                  onTap: () {
                    var yyDialog = YYDialog().build()
                      ..width = 120
                      ..borderRadius = 8.0
                      ..gravity = Gravity.rightTop
                      ..barrierColor = Colors.transparent
                      ..backgroundColor = QuhuiColors.miWhite
                      ..margin = EdgeInsets.only(top: 80, right: 20);
                    if (currentUser != null && currentUserId == post.userId) {
                      yyDialog
                        // ..textClick(
                        //     padding:
                        //         EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 16.0),
                        //     text: "修改",
                        //     fontSize: 16.0,
                        //     color: Colors.grey[700],
                        //     onClick: () {
                        //       NavigatorUtils.goPostCreate(
                        //           context, post.interestId, postId: post.id);
                        //     })
                        ..textClick(
                            padding:
                                EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 16.0),
                            text: "删除",
                            fontSize: 16.0,
                            color: Colors.grey[700],
                            onClick: () {
                              PostApi.builder()
                                  .deletePost(widget.postId)
                                  .then((value) {
                                    NavigatorUtils.ThrioNavigatorPop();
                              });
                            });
                    }
                    yyDialog.show();
                  },
                  child: Icon(
                    MIcon.more_vert,
                    color: QuhuiColors.primaryDarkValue,
                  ),
                )
              : InkWell(
                  onTap: () {
                    trueDebugPrint("click share");
                    _onShare(context);
                    // NavigatorUtils.goSharePage(context, post);
                  },
                  child: Icon(
                    MIcon.share,
                    color: QuhuiColors.primaryDarkValue,
                  ),
                );
          break;
        default:
          return Container();
          break;
      }
    });
  }

  _onShare(BuildContext context) async {
    // A builder is used to retrieve the context immediately
    // surrounding the RaisedButton.
    //
    // The context's `findRenderObject` returns the first
    // RenderObject in its descendent tree when it's not
    // a RenderObjectWidget. The RaisedButton's RenderObject
    // has its position and size after it's built.
    final RenderBox box = context.findRenderObject();
    // if (post.thumbnail.isNotEmpty) {
    //   await Share.shareFiles([post.thumbnail],
    //       text: post.title,
    //       subject: "趣会文章分享",
    //       sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
    // } else {
    AppVersion _lastAppVersion = appVersion;
    var shareText = "趣会文章分享 ${post.title} 下载地址${_lastAppVersion.url}";
    await Share.share(shareText,
        subject: "趣会文章分享",
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
    // }
  }
}
